package cn.newgrand.netcall.consultant.ui;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;

import cn.newgrand.netcall.consultant.SpecialistVCardManager;
import cn.newgrand.smackx.consultant.ConsultantManager;
import cn.newgrand.smackx.consultant.packet.SpecialistVCard;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * UI to display VCard Information in Wizards, Dialogs, Chat Rooms and any other container.
 *
 * @author Derek DeMoro
 */
public class SpecialistVCardVeiwer extends JPanel {

    private Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR);
    private Cursor LINK_CURSOR = new Cursor(Cursor.HAND_CURSOR);

    private final JLabel avatarImage;
    
    
//    private String firstName;
//    private String lastName;
    final JLabel usernameLabel = new JLabel();
    final JLabel workPhoneLabel = new JLabel();
    final JLabel cellPhoneLabel = new JLabel();
    final JLabel orgLabel = new JLabel();
    final JLabel spidLabel = new JLabel();
    final JLabel spRealName = new JLabel();
    final JLabel spSpeciality = new JLabel(); 
    private Boolean isUpdating = true;
    

    private String emailAddress = "";

    /**
     * Generate a VCard Panel using the specified jid.
     *
     * @param jid the jid to use when retrieving the vcard information.
     */
    public SpecialistVCardVeiwer(final String spid) {
        setLayout(new GridBagLayout());
        setOpaque(false);

        avatarImage = new JLabel();
        add(avatarImage, new GridBagConstraints(0, 0, 1, 3, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));


        Image aImage = SparkRes.getImageIcon(SparkRes.BLANK_24x24).getImage();
        aImage = aImage.getScaledInstance(-1, 64, Image.SCALE_SMOOTH);
        ImageIcon ico = new ImageIcon(aImage);

        avatarImage.setIcon(ico);

        final SwingWorker vcardLoader = new SwingWorker() {
        	SpecialistVCard vcard = null;

            public Object construct() {
            	if(SpecialistVCardManager.getInstance().isExistSpecialistVCard(spid)){
            		vcard = SpecialistVCardManager.getInstance().getSpecialistVCard(spid);
            	}else{
            		vcard = ConsultantManager.getInstance(SparkManager.getConnection()).getSpecialistVCard(spid);
            		SpecialistVCardManager.getInstance().addSecialistVCard(spid, vcard);
            	}
                return vcard;
            }

            public void finished() {
                if (vcard == null) {
                    // Do nothing.
                    return;
                }

                ImageIcon icon = null;

//                byte[] bytes = vcard.getAvatar();
//                if (bytes != null && bytes.length > 0) {
//                    try {
//                        icon = new ImageIcon(bytes);
//                        Image aImage = icon.getImage();
//                        aImage = aImage.getScaledInstance(-1, 48, Image.SCALE_SMOOTH);
//                        icon = new ImageIcon(aImage);
//                    }
//                    catch (Exception e) {
//                        Log.error(e);
//                    }
//                }
//                else {
//                    icon = SparkRes.getImageIcon(SparkRes.DEFAULT_AVATAR_32x32_IMAGE);
//                }
                icon = SparkRes.getImageIcon(SparkRes.BLANK_24x24);
                if (icon != null && icon.getIconWidth() > 0) {
                    avatarImage.setIcon(icon);
                    avatarImage.setBorder(BorderFactory.createBevelBorder(0, Color.white, Color.lightGray));
                }

//                vcard.setJabberId(jid);
                buildUI(vcard);
            }
        };

        vcardLoader.start();
    }

//    private void buildUI(final VCard vcard) {
//
//        avatarImage.addMouseListener(new MouseAdapter() {
//            public void mouseClicked(MouseEvent mouseEvent) {
//                if (mouseEvent.getClickCount() == 2) {
//                    SparkManager.getVCardManager().viewProfile(vcard.getJabberId(), avatarImage);
//                }
//            }
//        });
//
//        firstName = vcard.getFirstName();
//        if (firstName == null) {
//            firstName = "";
//        }
//
//        lastName = vcard.getLastName();
//        if (lastName == null) {
//            lastName = "";
//        }
//
//
//        
//        usernameLabel.setHorizontalTextPosition(JLabel.LEFT);
//        usernameLabel.setFont(new Font("Dialog", Font.BOLD, 15));
//
//        usernameLabel.setForeground(Color.GRAY);
//        if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) {
//            usernameLabel.setText( lastName+ " " + firstName);
//        }
//        else {
//            String nickname = SparkManager.getUserManager().getUserNicknameFromJID(jid);
//            usernameLabel.setText(UserManager.unescapeJID(nickname));
//        }
//
//
//        final Icon icon = SparkManager.getChatManager().getIconForContactHandler(vcard.getJabberId());
//        if (icon != null) {
//            usernameLabel.setIcon(icon);
//        }
//
//
//        add(usernameLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 0), 0, 0));
//
//        String title = vcard.getField("TITLE");
//        if (ModelUtil.hasLength(title)) {
//            final JLabel titleLabel = new JLabel(title);
//            titleLabel.setFont(new Font("Dialog", Font.PLAIN, 12));
//            add(titleLabel, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 0, 0), 0, 0));
//        }
//
//
//        if (ModelUtil.hasLength(vcard.getEmailHome())) {
//            emailAddress = vcard.getEmailHome();
//        }
//
//        final Color linkColor = new Color(49, 89, 151);
//        final String unselectedText = "<html><body><font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + emailAddress + "</u></font></body></html>";
//        final String hoverText = "<html><body><font color=red><u>" + emailAddress + "</u></font></body></html>";
//        final JLabel emailTime = new JLabel(unselectedText);
//        emailTime.addMouseListener(new MouseAdapter() {
//            public void mouseClicked(MouseEvent e) {
//                startEmailClient(emailAddress);
//            }
//
//            public void mouseEntered(MouseEvent e) {
//                emailTime.setText(hoverText);
//                setCursor(LINK_CURSOR);
//
//            }
//
//            public void mouseExited(MouseEvent e) {
//                emailTime.setText(unselectedText);
//                setCursor(DEFAULT_CURSOR);
//            }
//        });
//
//
//        add(emailTime, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 5, 0), 0, 0));
//
//        // Add JID Label
//        final String jid = UserManager.unescapeJID(vcard.getJabberId());
//        final JLabel jidLabel = new JLabel();
//        ResourceUtils.resLabel(jidLabel,"<html><body>"+Res.getString("label.vcard.jid")+":"+"<font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + jid + "</u></font></body></html>");
//        jidLabel.setToolTipText(Res.getString("tooltip.vcard.copy.jid"));
//        jidLabel.addMouseListener(new MouseAdapter() {
//            public void mouseEntered(MouseEvent mouseEvent) {
//                jidLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
//            }
//
//            public void mouseExited(MouseEvent mouseEvent) {
//                jidLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
//
//            }
//
//            public void mouseClicked(MouseEvent mouseEvent) {
//                SparkManager.setClipboard(jid);
//            }
//        });
//
//        add(jidLabel, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
//
//        // Add Home Phone
////        String homeNumber = vcard.getPhoneHome("VOICE");
////        if (!ModelUtil.hasLength(homeNumber)) {
////            homeNumber = "";
////        }
////        final JLabel homePhoneLabel = new JLabel();
////        ResourceUtils.resLabel(homePhoneLabel,Res.getString("label.vcard.home.phone")+": " + homeNumber);
////        add(homePhoneLabel, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
//
//        // Add Work Phone
//        String workNumber = vcard.getPhoneWork("VOICE");
//        if (!ModelUtil.hasLength(workNumber)) {
//            workNumber = "";
//        }
//        
//        ResourceUtils.resLabel(workPhoneLabel,Res.getString("label.vcard.work.phone")+": " + workNumber);
//        add(workPhoneLabel, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
//
//        // Add Cell Phone
//        String cellNumber = vcard.getPhoneWork("CELL");
//        if (!ModelUtil.hasLength(cellNumber)) {
//            cellNumber = "";
//        }
//
//        
//        ResourceUtils.resLabel(cellPhoneLabel,Res.getString("label.vcard.home.cell")+": " + cellNumber);
//        add(cellPhoneLabel, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
//
//        // Add Company
//        String company = vcard.getOrganization();
//        
//        
//        ResourceUtils.resLabel(orgLabel,Res.getString("label.vcard.work.company") + ": "+company);
//        add(orgLabel, new GridBagConstraints(1, 6, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
//        
//        //add update button
//        String update = Res.getString("button.update.vcard");
//        final JLabel updateLabel = new JLabel();
//        ResourceUtils.resLabel(updateLabel,"<html><body><font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + Res.getString("button.update.vcard") + "</u></font></body></html>");
//        add(updateLabel, new GridBagConstraints(2, 7, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 2, 0), 0, 0));
//        
//        updateLabel.addMouseListener(new MouseAdapter() {
//            public void mouseEntered(MouseEvent mouseEvent) {
//            		updateLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
//            }
//
//            public void mouseExited(MouseEvent mouseEvent) {
//            	updateLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
//            }
//
//            public void mouseClicked(MouseEvent mouseEvent) {
//            	
//				if (isUpdating) {
//					isUpdating = false;
//					SparkManager.getVCardManager().addToQueue(jid);
//					TaskEngine te = TaskEngine.getInstance();
//					te.schedule(new TimerTask() {
//						public void run() {
//							VCard vcardTemp = SparkManager.getVCardManager()
//									.getVCard(jid);
//							updateViewer(vcardTemp);
//							isUpdating = true;
//						}
//					}, 3000);
//				}
//            	
//            }
//        });
//
//    }
//    
//    public void updateViewer(VCard vcard){
//    	String workNumber = vcard.getPhoneWork("VOICE");
//        if (!ModelUtil.hasLength(workNumber)) {
//            workNumber = "";
//        }
//        String cellNumber = vcard.getPhoneWork("CELL");
//        if (!ModelUtil.hasLength(cellNumber)) {
//            cellNumber = "";
//        }
//        String company = vcard.getOrganization();
//        ResourceUtils.resLabel(workPhoneLabel,Res.getString("label.vcard.work.phone")+": " + workNumber);
//        ResourceUtils.resLabel(cellPhoneLabel,Res.getString("label.vcard.home.cell")+": " + cellNumber);
//        ResourceUtils.resLabel(orgLabel,Res.getString("label.vcard.work.company") + ": "+company);
//        
//    }

    private void buildUI(final SpecialistVCard vcard) {

//        avatarImage.addMouseListener(new MouseAdapter() {
//            public void mouseClicked(MouseEvent mouseEvent) {
//                if (mouseEvent.getClickCount() == 2) {
//                    SparkManager.getVCardManager().viewProfile(vcard.getJabberId(), avatarImage);
//                }
//            }
//        });

//        firstName = vcard.getFirstName();
//        if (firstName == null) {
//            firstName = "";
//        }
//
//        lastName = vcard.getLastName();
//        if (lastName == null) {
//            lastName = "";
//        }


        
        usernameLabel.setHorizontalTextPosition(JLabel.LEFT);
        usernameLabel.setFont(new Font("Dialog", Font.BOLD, 15));

        usernameLabel.setForeground(Color.GRAY);
//        if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) {
//            usernameLabel.setText( lastName+ " " + firstName);
//        }
//        else {
//            String nickname = SparkManager.getUserManager().getUserNicknameFromJID(jid);
//            usernameLabel.setText(UserManager.unescapeJID(nickname));
//        }


//        final Icon icon = SparkManager.getChatManager().getIconForContactHandler(vcard.getJabberId());
//        if (icon != null) {
            usernameLabel.setIcon(SparkRes.getImageIcon(SparkRes.EARTH_VIEW_16x16));
//        }


        add(usernameLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 0), 0, 0));

//        String title = vcard.getFieldValue("TITLE");
//        if (ModelUtil.hasLength(title)) {
//            final JLabel titleLabel = new JLabel(title);
//            titleLabel.setFont(new Font("Dialog", Font.PLAIN, 12));
//            add(titleLabel, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 0, 0), 0, 0));
//        }


        if (ModelUtil.hasLength(vcard.getFieldValue("email"))) {
            emailAddress = vcard.getFieldValue("email");
        }

        final Color linkColor = new Color(49, 89, 151);
        final String unselectedText = "<html><body><font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + emailAddress + "</u></font></body></html>";
        final String hoverText = "<html><body><font color=red><u>" + emailAddress + "</u></font></body></html>";
        final JLabel emailTime = new JLabel(unselectedText);
        emailTime.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                startEmailClient(emailAddress);
            }

            public void mouseEntered(MouseEvent e) {
                emailTime.setText(hoverText);
                setCursor(LINK_CURSOR);

            }

            public void mouseExited(MouseEvent e) {
                emailTime.setText(unselectedText);
                setCursor(DEFAULT_CURSOR);
            }
        });


        add(emailTime, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 5, 0), 0, 0));

        // Add JID Label
        final String jid = vcard.getFieldValue("spjid");
        final String spid = vcard.getFieldValue("spid");
        final JLabel jidLabel = new JLabel();
        ResourceUtils.resLabel(jidLabel,"<html><body>"+Res.getString("label.vcard.jid")+":"+"<font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + jid + "</u></font></body></html>");
        jidLabel.setToolTipText(Res.getString("tooltip.vcard.copy.jid"));
        jidLabel.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent mouseEvent) {
                jidLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
            }

            public void mouseExited(MouseEvent mouseEvent) {
                jidLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

            }

            public void mouseClicked(MouseEvent mouseEvent) {
                SparkManager.setClipboard(jid);
            }
        });

        add(jidLabel, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));

        // Add Home Phone
//        String homeNumber = vcard.getPhoneHome("VOICE");
//        if (!ModelUtil.hasLength(homeNumber)) {
//            homeNumber = "";
//        }
//        final JLabel homePhoneLabel = new JLabel();
//        ResourceUtils.resLabel(homePhoneLabel,Res.getString("label.vcard.home.phone")+": " + homeNumber);
//        add(homePhoneLabel, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));

        // Add Work Phone
        String workNumber = vcard.getFieldValue("VOICE");
        if (!ModelUtil.hasLength(workNumber)) {
            workNumber = "";
        }
        
        ResourceUtils.resLabel(workPhoneLabel,Res.getString("label.vcard.work.phone")+": " + workNumber);
        add(workPhoneLabel, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));

        // Add Cell Phone
        String cellNumber = vcard.getFieldValue("CELL");
        if (!ModelUtil.hasLength(cellNumber)) {
            cellNumber = "";
        }

        
        ResourceUtils.resLabel(cellPhoneLabel,Res.getString("label.vcard.home.cell")+": " + cellNumber);
        add(cellPhoneLabel, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));

        // Add Company
        String company = vcard.getFieldValue("company");
        
        
        ResourceUtils.resLabel(orgLabel,Res.getString("label.vcard.work.company") + ": "+company);
        add(orgLabel, new GridBagConstraints(1, 6, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 7, 2, 0), 0, 0));
        
        //add update button
        String update = Res.getString("button.update.vcard");
        final JLabel updateLabel = new JLabel();
        ResourceUtils.resLabel(updateLabel,"<html><body><font color=" + GraphicUtils.toHTMLColor(linkColor) + "><u>" + Res.getString("button.update.vcard") + "</u></font></body></html>");
        add(updateLabel, new GridBagConstraints(2, 7, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 2, 0), 0, 0));
        
        updateLabel.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent mouseEvent) {
            		updateLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
            }

            public void mouseExited(MouseEvent mouseEvent) {
            	updateLabel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            }

            public void mouseClicked(MouseEvent mouseEvent) {
            	
				if (isUpdating) {
					isUpdating = false;
					SparkManager.getVCardManager().addToQueue(jid);
					TaskEngine te = TaskEngine.getInstance();
					te.schedule(new TimerTask() {
						public void run() {
							SpecialistVCard vcardTemp = ConsultantManager.getInstance(SparkManager.getConnection()).getSpecialistVCard(spid);
							SpecialistVCardManager.getInstance().addSecialistVCard(spid, vcardTemp);
							updateViewer(vcardTemp);
							isUpdating = true;
						}
					}, 3000);
				}
            	
            }
        });

    }
    
    public void updateViewer(SpecialistVCard vcard){
    	String workNumber = vcard.getFieldValue("VOICE");
        if (!ModelUtil.hasLength(workNumber)) {
            workNumber = "";
        }
        String cellNumber = vcard.getFieldValue("CELL");
        if (!ModelUtil.hasLength(cellNumber)) {
            cellNumber = "";
        }
        String company = vcard.getFieldValue("company");
        ResourceUtils.resLabel(workPhoneLabel,Res.getString("label.vcard.work.phone")+": " + workNumber);
        ResourceUtils.resLabel(cellPhoneLabel,Res.getString("label.vcard.home.cell")+": " + cellNumber);
        ResourceUtils.resLabel(orgLabel,Res.getString("label.vcard.work.company") + ": "+company);
        
    }
    
    private void startEmailClient(String emailAddress) {
        SparkManager.getNativeManager().launchEmailClient(emailAddress, "");
    }
}
